<style>
</style>
<script type="text/template" id="territory-manage-template">
    <div class="territory-manage">
        <div class="head">
            <div class="search">
                <input type="" name="" class="search-input" style="display: none;">
            </div>
            <div class="btn-area">
                <a href="javascript:;" class="add" title="Add" id="add-territory"></a>
                <a href="javascript:;" class="delete" title="Delete" id="delete-territory"></a>
               <!-- <a href="javascript:;" class="save" title="Save" id="save-territory"></a>-->
            </div>
        </div>
        <div class="territory-list">
            <!--data data-created是否是新创建 true是从数据获取的，false是新创建的 data-router Router的名字-->
            {{#each data}}
                <div class="items" data-name="{{title}}" data-router="{{router_title}}" data-driver="{{driver_id}}" data-vehicle="{{vehicle_id}}" data-points="{{points}}" data-created="true">{{title}}</div>
            {{/each}}
        </div>
        <div class="footer">
            <span class="yes-btn" id="yes-btn">确定</span>
        </div>
    </div>
</script>


<script>
    {
        //删除Territoy
        function deleteTerrity ( title = null)
        {
            title = title || CONFIG.territoryName;
            return new Promise( function (resolve , reject) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: CONFIG.deleteTerritory ,
                    data: {title:title,warehouse:CONFIG.wareHouseCode},
                    success: function (result) {
                        if(result.code==200){
                             resolve('SUCCESS');
                        }else{
                            reject('ERROR')
                        }
                    },
                    error : function() {
                        reject('ERROR')
                    }
                });
            })
        }

        //获取Territoy list 渲染到列表
        function getTerrioty()
        {

            $.ajax({
                type: "POST",
                dataType: "json",
                url: CONFIG.territoryList ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {
                    let data=[];
                    $.each(result.msg,function (index,value) {
                        let t={
                            driver_id:value.driver_id,
                            vehicle_id:value.vehicle_id,
                            points:JSON.stringify( value.points),
                            title:value.title,
                            router_title:value.router_title
                        }
                        data.push(t);
                    });
                    let source=$('#territory-manage-template').html();
                    let template = Handlebars.compile(source);
                    let html = template({data:data});
                    $.Pop(html,{Close:true,CloseBtn:true,Title:'Territory Manage'});
                },
                error : function() {
                }
            });

        }


        $('#territory-manage').click( function () {
            getTerrioty();
        });
        //添加Territoy
        $(document).on('click','#add-territory',function(){
            let html=`
                  <input id="add-territory-input" style="height: 30px;" placeholder="New Territory" />
                  <a style="text-decoration: none;padding: 5px 8px;background: #1f7fe4d6;color: white;" id="save-territory-value">保存</a>

            `;
            $.Pop(html,{CloseBtn:true,Title:'Add Territory',Btn:{yes:{vla:"确定"}}})
        });
        //删除Territoy
        $(document).on('click','#delete-territory',function(){
             if(confirm('你确定要删除吗'))
             {
                 let obj = $('.territory-list').find('.selected');
                 let title = $(obj).data('name');
                 $(obj).remove();
                 deleteTerrity(title).then(function (resolve) {
                     $.Pro('删除成功');
                 },function () {
                     $.Pro('删除失败');
                 });
             }
        });
        //监听Add Territory页面保存按钮
        $(document).on('click','#save-territory-value',function () {
            let territory = $('#add-territory-input').val();
                territory = territory.replace(/(^\s+)|(\s+$)/g,"");
            if(!territory){
                $.Pro('请输入 Territory');
                return false;
            }

            //填充到列表
            new Promise(  (reslove , reject)=> {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: CONFIG.checkTerritoryIsExist ,
                    data: {title:territory},
                    success: function (result) {
                        if(result.code!=200){
                            $.Pro('Territory 已存在！');
                            return false;
                        }
                        reslove('SUCCESS');
                    },
                    error : function() {}
                });
            }).then( (value)=> {
                $('.territory-list').prepend('<div class="items" data-name="'+territory+'" data-created="false">'+territory+'</div>');
                //关闭提示框
                $('#add-territory-input').val('');
                $(this).parent().prev().find('i').trigger('click');
            })

        });

        //
        $(document).on('click','.territory-list .items',function () {
            $(this).addClass('selected').siblings().removeClass('selected');
        });

        //选择Territory
        $(document).on('click','#yes-btn',function () {
            let obj = $('.territory-list').find('.selected');
            CONFIG.territoryName=$(obj).data('name');
            $(this).parent().parent().parent().prev().find('i').trigger('click');

            let created = obj.data('created');

            if( created == true)  //选择了History的数据 把History的数据显示在页面上
            {

                let poinst = $(obj).data('points');
                let driver = $(obj).data('driver').toString().split(',');
                let vehicle = $(obj).data('vehicle').toString().split(',');
                let router_title = $(obj).data('router').split(',');
                for(let i=0;i<poinst.length;i++)
                {
                    let routerId = md5(new Date().toDateString()+Math.random());    //生成一个随机id
                    //画多边形
                   // Polygon.draw( poinst[i],map , routerId );
                    //设置Router
                    OBJECT.routerPonits[routerId]=[];
                    OBJECT.routerPonits[routerId].vehicleId = vehicle[i];
                    OBJECT.routerPonits[routerId].driverId = driver[i];
                    OBJECT.routerPonits[routerId].UpdateStatus = false;   //设置不更新到服务器
                    CONFIG.optimizeOrderpoints[routerId] = true;         //对新的站点顺序进行排序
                    OBJECT.routersNameMap[routerId] = router_title[i];
                    OBJECT.routerEdgePoints[routerId] = poinst[i];
                    OBJECT.routersBgColorMap[routerId] = getRandomColor();
                    Queue(routerId)

                }
            }




        });
        //保存terrioty
        $(document).on('click','#save-territory', function () {
              if(!CONFIG.territoryName)
              {
                  $.Pro('请选择一个territory')
                  return false;
              }
              let promise=[];
              let i=0;
              //遍历所有多边形的顶点
              for(let routerId in OBJECT.routerEdgePoints)
              {

                  let router = OBJECT.routerPonits[routerId];
                  let data={
                      routerId:routerId,
                      warehouse:CONFIG.wareHouseCode,
                      title:CONFIG.territoryName,
                      driver_id:router.driverId || '',
                      vehicle_id:router.vehicleId || '',
                      router_title:OBJECT.routersNameMap[routerId],
                      points:JSON.stringify( OBJECT.routerEdgePoints[routerId] )
                  }
                  promise[i] =  function () {
                      $.ajax({
                          type: "POST",
                          dataType: "json",
                          url: CONFIG.saveTerritory ,
                          data: data,
                          success: function (result) {
                          },
                          error : function() {
                          }
                      });
                  }
                  i++;
              }
              deleteTerrity().then(function (value) {
                  promise.forEach(function (value,index) {
                       promise[index]();
                  },function (error) {
                      console.log(error)
                  })
              })
        });

    }
</script>

